package com.hksj.Intelligentmanagement.config;

import com.hksj.Intelligentmanagement.utils.FastJsonRedisSerializer;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private Integer port;

    @Value("${spring.redis.password}")
    private String password;

    @Bean
    @SuppressWarnings(value = { "unchecked", "rawtypes" })
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
    {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        FastJsonRedisSerializer serializer = new FastJsonRedisSerializer(Object.class);

        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);

        // Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);

        template.afterPropertiesSet();
        return template;
    }

    //redisson的配置
    @Bean
    public Redisson redisson(){
        //单机模式
        Config config = new Config();
        //初始化配置 使用单机模式 使用redis的数据库0
        config.useSingleServer().setAddress("redis://"+ host + ":" + port);
        if (StringUtils.isNotEmpty(password)){
            //如果redis密码不为空 则一定要配置，不然会报错。如果密码为空一定不要配置,哪怕setPassword(null)也会报错
            config.useSingleServer().setPassword(password);
        }
        //redis数据库使用0号数据库
        config.useSingleServer().setDatabase(1);
        //返回创建redisson
        return (Redisson) Redisson.create(config);
    }

}
